package com.example.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;


public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        String path = request.getContextPath() ;
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        //教师和管理员重点向到后台
        if (roles.contains("ROLE_teacher") || roles.contains("ROLE_root")){
                try {
                    response.sendRedirect(basePath+"back/index");
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }else{
                try {
                    response.sendRedirect(basePath+"index");
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }
}